package com.common.app.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.Nullable;


import com.common.app.R;
import com.common.base.utils.ViewUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class SideIndexBar extends View {
    private static final String[] DEFAULT_INDEX_ITEMS = {"热", "A", "B", "C", "D", "E", "F", "G", "H",
            "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    private List<String> mIndexItems;
    private float mItemHeight = 0; //每个index的高度
    private int mTextSize;      //sp
    private int mTextColor;
    private int mTextTouchedColor;
    private int mCurrentIndex = -1;

    private Paint mPaint;
    private Paint mTouchedPaint;

    private int mWidth;
    private int mHeight;
    private float mTopMargin = 0;   //居中绘制，文字绘制起点和控件顶部的间隔
    private String mChooseItem = ""; // 记录选中的字母
    private TextView mOverlayTextView;
    private OnIndexTouchedChangedListener mOnIndexChangedListener;
    private int mPosition;

    private int navigationBarHeight;
    private Bitmap hotSourceBitmap, hotScaleBitmap;

    public SideIndexBar(Context context) {
        this(context, null);
    }

    public SideIndexBar(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SideIndexBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public void setNavigationBarHeight(int height) {
        this.navigationBarHeight = height;
    }

    public void setIndexItems(List<String> items) {
        if (items == null || items.size() == 0) {
            return;
        }
        mIndexItems.clear();
        mIndexItems.add(getResources().getString(R.string.match_event_filter_title_hot));
        mIndexItems.addAll(items);
        mChooseItem = mIndexItems.get(0);// 获取第一个字母
        //重新获取item,marginTop
        if (mIndexItems.size() > 0) {
            mTopMargin = (mHeight - mItemHeight * mIndexItems.size()) / 2;
        }
    }

    private void init(Context context) {
        mIndexItems = new ArrayList<>();
        mIndexItems.addAll(Arrays.asList(DEFAULT_INDEX_ITEMS));
        TypedValue typedValue = new TypedValue();
        context.getTheme().resolveAttribute(R.attr.cpIndexBarTextSize, typedValue, true);
//        mTextSize = context.getResources().getDimensionPixelSize(typedValue.resourceId);

        context.getTheme().resolveAttribute(R.attr.cpIndexBarNormalTextColor, typedValue, true);
        mTextColor = context.getResources().getColor(R.color.color_323232);

        context.getTheme().resolveAttribute(R.attr.cpIndexBarSelectedTextColor, typedValue, true);
        mTextTouchedColor = context.getResources().getColor(R.color.color_323232);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setTextSize(ViewUtils.INSTANCE.sp2px(10f));
        mPaint.setColor(mTextColor);

        mTouchedPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTouchedPaint.setTextSize(ViewUtils.INSTANCE.sp2px(16f));
        mTouchedPaint.setColor(mTextTouchedColor);

        hotSourceBitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_filter_hot);
        hotScaleBitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_filter_hot_selected);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        String index;
        int t = (int) mTopMargin;//top的基准点(支持padding)
        Paint.FontMetrics fontMetrics = mPaint.getFontMetrics();
        float v = fontMetrics.bottom - fontMetrics.top;
        for (int i = 0; i < mIndexItems.size(); i++) {
            index = mIndexItems.get(i);
            Paint.FontMetrics fm = mPaint.getFontMetrics();
            int baseline = (int) ((mItemHeight - fm.bottom - fm.top) / 2);//计算出在每格index区域，竖直居中的baseLine值
            if (index.equals(mChooseItem)) {
                Paint paint = new Paint();
                paint.setTextSize(ViewUtils.INSTANCE.sp2px(14f));
                paint.setColor(getResources().getColor(R.color.color_323232));
                paint.setFlags(Paint.ANTI_ALIAS_FLAG);


                if (getResources().getString(R.string.match_event_filter_title_hot).equals(index)) {
                    canvas.drawBitmap(hotScaleBitmap, (mWidth - hotScaleBitmap.getWidth()) / 2, t + mItemHeight / 2 * i, i == mCurrentIndex ? mTouchedPaint : paint);
                } else {
                    canvas.drawText(index, (mWidth - paint.measureText(index)) / 2, t + mItemHeight * i + baseline, i == mCurrentIndex ? mTouchedPaint : paint);
                }
            } else {
                if (getResources().getString(R.string.match_event_filter_title_hot).equals(index)) {
                    canvas.drawBitmap(hotSourceBitmap, (mWidth - hotSourceBitmap.getWidth()) / 2, t + mItemHeight / 2 * i, i == mCurrentIndex ? mTouchedPaint : mPaint);
                } else {
                    canvas.drawText(index, (mWidth - mPaint.measureText(index)) / 2, t + mItemHeight * i + baseline, i == mCurrentIndex ? mTouchedPaint : mPaint);
                }
            }
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        mWidth = getWidth();
        if (Math.abs(h - oldh) == navigationBarHeight) {
            //底部导航栏隐藏或显示
            mHeight = h;
        } else {
            //避免软键盘弹出时挤压
            mHeight = Math.max(getHeight(), oldh);
        }
        if (mIndexItems.size() > 0) {
            mItemHeight = mHeight / mIndexItems.size();
            mTopMargin = (mHeight - mItemHeight * mIndexItems.size()) / 2;
        }
    }

    @Override
    public boolean performClick() {
        return super.performClick();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        performClick();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                float y = event.getY();
                int indexSize = mIndexItems.size();
                int touchedIndex = (int) ((y - mTopMargin) / mItemHeight);
                if (touchedIndex < 0) {
                    touchedIndex = 0;
                } else if (touchedIndex >= indexSize) {
                    touchedIndex = indexSize - 1;
                }
                if (mOnIndexChangedListener != null && touchedIndex >= 0 && touchedIndex < indexSize) {
                    if (touchedIndex != mCurrentIndex) {
                        mCurrentIndex = touchedIndex;
                        if (mOverlayTextView != null) {
                            mOverlayTextView.setVisibility(VISIBLE);
                            if ("热门赛事".equals(mIndexItems.get(touchedIndex))) {
                                mOverlayTextView.setText("热");
                            } else {
                                mOverlayTextView.setText(mIndexItems.get(touchedIndex));
                            }
                        }
                        mOnIndexChangedListener.onIndexChanged(mIndexItems.get(touchedIndex), touchedIndex);
                        invalidate();
                    }
                }
                mChooseItem = mIndexItems.get(touchedIndex);
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                mCurrentIndex = -1;
                if (mOverlayTextView != null) {
                    mOverlayTextView.setVisibility(GONE);
                }
                invalidate();
                break;
        }
        return true;
    }

    public SideIndexBar setOverlayTextView(TextView overlay) {
        this.mOverlayTextView = overlay;
        return this;
    }

    public SideIndexBar setOnIndexChangedListener(OnIndexTouchedChangedListener listener) {
        this.mOnIndexChangedListener = listener;
        return this;
    }

    public interface OnIndexTouchedChangedListener {
        void onIndexChanged(String index, int position);
    }


    public void setScrollPosition(int position) {
        this.mPosition = position;
        if (position >= 0 && position < mIndexItems.size()) {
            mChooseItem = mIndexItems.get(position);
            invalidate();
        }
    }

    public int getPositionByKey(String key) {
        return mIndexItems.indexOf(key);
    }
}
